<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/8/24  19:25
 */
namespace app\business\controller;
use app\api\logic\System;
use think\Request;
use think\Db;
use think\Page;
class Goods extends Common
{
    /**
     * @return 商品列表
     */
    public function index()
    {
        $shop_id= $this->user['shopid'];
        $db_goods=db("goods");
        $data['shop_id']=$shop_id;
        if(isset($this->requestData['status']) && !empty($this->requestData['status'])){
            $data['status'] = $this->requestData['status'];
        }else {
            $data['status'] = array("gt", -1);
        }
        if(isset($this->requestData['cid']) && !empty($this->requestData['cid'])){
            $data['cid'] = $this->requestData['cid'];
        }
        if(isset($this->requestData['name'])){
            $data['name'] =array("like",'%'.$this->requestData['name'].'%');
        }
        $p=input('page','1');
        $size=isset($this->requestData['limit'])?$this->requestData['limit']:'10';
        $goods=$db_goods->where($data)->page($p,$size)->order("id desc")->select();
        $db_order=db("order");
        foreach($goods as &$v){
            $v['image']=IMG_PATH.$v['image'];
            $or['og.goods_id'] = $v['id'];
            $or['o.status'] = '3';
            $or['o.finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
            $v['ordernum'] = $db_order->alias("o")
                ->join("order_goods og","og.order_id=o.id")
                ->where($or)->count();
        }
        $count=$db_goods->where($data)->count();
        $result['list'] = $goods;
        $result['count'] = $count;;
        $result['page_num']=$p;
        $result['page_limit']=$size;

        $goods=$result;
        $page=new Page($goods['count'],$goods['page_limit']);
        $goods['page'] = $page;
        $category=(new System())->category();
        $this->assign("data",$goods);
        $this->assign("category",$category);
        $this->assign("status",input('status'));
        $this->assign("cid",input('cid'));
        $this->assign("name",input('name'));
        return $this->fetch();
    }
    /**
     * @throws 商品上下架
     */
    public function goods_status()
    {
        $id = input('id/d');
        $db_goods=db("goods");
        $goods=$db_goods->where("id='$id' and shop_id=".$this->user['id']) ->find();
        if(!$goods){
            exit(json_encode("商品不存在"));
        }
        if($goods['status']==0){
            $data['status']=1;
        }else{
            $data['status']=0;
        }
        $del =$db_goods
            ->where("id='$id' and shop_id=".$this->user['id'])
            ->update($data);
        if($del){
            exit(json_encode(1));
        }else{
            exit(json_encode("操作失败"));
        }
    }
    /**
     * @throws 删除商品
     */
    public function goods_del()
    {
        $id = input('id/d');
        $db_goods=db("goods");
        $goods=$db_goods->where("id='$id' and shop_id=".$this->user['id']) ->find();
        if(!$goods){
            exit(json_encode("商品不存在"));
        }
        $del =$db_goods
            ->where("id='$id' and shop_id=".$this->user['id'])
            ->update(["status"=>"-1"]);
        if($del){
            exit(json_encode(1));
        }else{
            exit(json_encode("删除失败"));
        }
    }
    /**
     * 订单列表导出excel
     */
    public function export($where)
    {

        $headArr = array("订单号","昵称","收货人姓名","收货号码","省份","城市","区/县","详细地址","下单时间","支付时间",
            '发货时间','完成时间',"商品名称","数量","规格","价格","状态");
        //$where['status']=1;
        $list = db("order")->alias("o")
            ->field("o.*,m.nickname,m.headimage,g.goods_name,g.goods_num,g.goods_price,g.spec_name")
            ->join("member m","o.uid=m.id")
            ->join("order_goods g","g.order_id=o.id")
            ->order("id desc")
            ->where($where)
            ->select();
        $data=array();
        foreach($list as $k => $v){
            $data[$k][] = $v['order_sn'];
            $data[$k][] = $v['nickname'];
            $data[$k][] = $v['name'];
            $data[$k][] = $v['mobile'];
            $data[$k][] = $v['province'];
            $data[$k][] = $v['city'];
            $data[$k][] = $v['county'];
            $data[$k][] = $v['address'];
            $data[$k][] = date("Y-m-d H:i",$v['create_time']);
            $data[$k][] =!empty($v['pay_time'])?date("Y-m-d H:i",$v['pay_time']):'';
            $data[$k][] = !empty($v['shipping_time'])?date("Y-m-d H:i",$v['shipping_time']):'';
            $data[$k][] = !empty($v['finish_time'])?date("Y-m-d H:i",$v['finish_time']):'';
            $data[$k][] = $v['goods_name'];
            $data[$k][] = $v['goods_num'];
            $data[$k][] = $v['spec_name'];
            $data[$k][] = $v['goods_price'];
            //,0待付款，1已付款，2已发货，3已完成,,4退款中，-2已关闭，-1已退款
            switch($v['status']){
                case '0': $data[$k][]='待付款';break;
                case '1': $data[$k][]='已付款';break;
                case '2': $data[$k][]='已发货';break;
                case '3': $data[$k][]='已完成';break;
                case '4': $data[$k][]='退款中';break;
                case '-1': $data[$k][]='已退款';break;
                case '-2': $data[$k][]='已关闭';break;
            }
        }
        $filename='订单列表';
        (new Export())->ImportExcel($filename,$headArr,$data);
    }
    public function goodsadd()
    {
        $category=(new System())->category();
        if(request()->isAjax()) {
        $shop_id = $this->user['shopid'];
        $db_goods = db("goods");
        $des = input('des');
        $keepday = input('keepday');
        $unit = input('unit');
        $data = [
            'name' => input('name'),
            'des' => isset($des) ? $des : '',
            'keepday' => isset($keepday) ? $keepday : '',
            'label' => input('label'),
            'cid' => input('cid'),
            'price' => input('price'),
            'oldprice' => input('oldprice'),
            'stock' => input('stock'),
            'unit' => isset($unit) ? $unit : '',
            "shop_id" => $shop_id,
        ];
        $file = request()->file('image');
        if ($file) {
            $info = $file->move('./static/uploads');
            if ($info) {
                $data['image'] = '/'.$info->getSaveName();
            }
        }
        $images = request()->file('images');
        $images_name = [];
        foreach($images as $file){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move('./static/uploads');
            if($info){
                if(empty($images_name)){
                    $images_name[] = '/'.$info->getSaveName();
                }else{
                    array_push($images_name, $info->getSaveName());
                }
            }
            if($images_name) {
                $data['imgs'] = serialize($images_name);
            }
        }
        $id = input('id');
        if (isset($id) && !empty($id)) {
            $goods = $db_goods->where("id=" . $id)->find();
            if (is_file(ROOT_PATH . 'public/static/uploads/' . $goods['image'])) {
                unlink(ROOT_PATH . 'public/static/uploads/' . $goods['image']);
            }
           //
            Db::startTrans();
            try {
                $res = $db_goods->where("id=" . $id)->update($data);
                if($res===false)  throw new \Exception('修改失败');
                $specs = input('specs');
                if (isset($specs)) {
                    $specs = json_decode($specs,1);

                    if(!empty($specs) && is_array($specs)){



                        $spec_id_array = array_column($specs, 'id');

                        $db_option = db("goods_option");

                        //先清空商品规格在重新插数据
                        $where['goodsid'] = $id;
                        $db_option->where($where)->delete();

                        
                        foreach ($specs as $k => $v) {
                            $option = array(
                                "title" => $v['title'],
                                "stock" => $v['stock'],
                                "price" => $v['price'],
                                "goodsid" => input('id')
                            );

                            if(!empty($v['id'])){
                                $option['id'] = $v['id'];
                            }

                           $op_res= $db_option->insert($option);
                           if($op_res===false)  throw new \Exception('修改规格失败');
                        }
                    }
                }
                $parms = input('params');
                if (isset($parms)) {
                    $params = json_decode($parms,1);

                    if(!empty($params) && is_array($params)){


                        $param_id_array = array_column($params, 'id');
                        $db_param = db("goods_param");
                        unset($where);
                        $where['goodsid'] = $id;
                        $db_param->where($where)->delete();
                        
                        foreach ($params as $k => $v) {
                            $param = array(
                                "title" => $v['title'],
                                "param" => serialize($v['param']),
                                "goodsid" => input('id')
                            );

                            if(!empty($v['id'])){
                                $param['id'] = $v['id'];
                            }

                            $pa_res= $db_param->insert($param);
                            if($pa_res===false)  throw new \Exception('修改属性失败');
                        }
                    }
 
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return array("message"=>$e->getMessage());
            }

        } else {
            Db::startTrans();
            try {
                $res =$db_goods->insertGetId($data);
                if(!$res)  throw new \Exception('发布失败');
                $specs = input('specs');
                if (isset($specs)) {
                    $specs = json_decode($specs,1);
                    if(!empty($specs) && is_array($specs)){


                        $db_option = db("goods_option");
                        foreach ( $specs as $k => $v) {
                            $option = array(
                                "title" => $v['title'],
                                "stock" => $v['stock'],
                                "price" => $v['price'],
                                "goodsid" => $res,
                            );
                           $op_add=$db_option->insert($option);
                            if(!$op_add)  throw new \Exception('添加规格失败');
                        }
                    }
                }
                $parms = input('params');
                if (isset($parms)) {

                    $params = json_decode($parms,1);

                    if(!empty($params) && is_array($params)){


                        $db_param = db("goods_param");
                        foreach ($params as $k => $v) {
                            $param = array(
                                "title" => $v['title'],
                                "param" => serialize($v['param']),
                                "goodsid" => $res,
                            );
                            $pa_add=$db_param->insert($param);
                            if(!$pa_add)  throw new \Exception('添加属性失败');
                        }
                    }
                }
         Db::commit();
        } catch (\Exception $e) {
        Db::rollback();
                return array("message"=>$e->getMessage());
    }
            if ($res === false) return array("message" => '操作失败');
            return array();
        }
        }
        $this->assign("category",$category);
        return $this->fetch();
    }
    public function goodsedit()
    {
        if(request()->isAjax()) {
        $shop_id = $this->user['shopid'];
        $db_goods = db("goods");
        $des = input('des');
        $keepday = input('keepday');
        $unit = input('unit');
        $data = [
            'name' => input('name'),
            'des' => isset($des) ? $des : '',
            'keepday' => isset($keepday) ? $keepday : '',
            'label' => input('label'),
            'cid' => input('cid'),
            'price' => input('price'),
            'oldprice' => input('oldprice'),
            'stock' => input('stock'),
            'unit' => isset($unit) ? $unit : '',
            "shop_id" => $shop_id,
        ];
        $file = request()->file('image');
        if ($file) {
            $info = $file->move('./static/uploads');
            if ($info) {
                $data['image'] = '/'.$info->getSaveName();
            }
        }
        $id = input('id');
        $images = request()->file('images');
        $imgs = $db_goods->where("id=" . $id)->value('imgs');
        $images_name = [];
        if(!empty($imgs)){$images_name = unserialize($imgs);}
		if(isset($images) && in_array($images)){
			foreach($images as $file){
				// 移动到框架应用根目录/public/uploads/ 目录下
				$info = $file->move('./static/uploads');
				if($info){
					if(empty($images_name)){
						$images_name[] = '/'.$info->getSaveName();
					}else{
						array_push($images_name, $info->getSaveName());
					}
				}
				if($images_name) {
					$data['imgs'] = serialize($images_name);
				}
			}
		}

        if (isset($id) && !empty($id)) {
            $goods = $db_goods->where("id=" . $id)->find();
            if (is_file(ROOT_PATH . 'public/static/uploads/' . $goods['image'])) {
                unlink(ROOT_PATH . 'public/static/uploads/' . $goods['image']);
            }
           //
            Db::startTrans();
            try {
                $res = $db_goods->where("id=" . $id)->update($data);
                if($res===false)  throw new \Exception('修改失败');
                $specs = input('specs');
                if (isset($specs)) {
                    $specs = json_decode($specs,1);

                    if(!empty($specs) && is_array($specs)){

                        $spec_id_array = array_column($specs, 'id');

                        $db_option = db("goods_option");

                        //先清空商品规格在重新插数据
                        $where['goodsid'] = $id;
                        $db_option->where($where)->delete();

                        
                        foreach ($specs as $k => $v) {
                            $option = array(
                                "title" => $v['title'],
                                "stock" => $v['stock'],
                                "price" => $v['price'],
                                "goodsid" => input('id')
                            );

                            if(!empty($v['id'])){
                                $option['id'] = $v['id'];
                            }

                           $op_res= $db_option->insert($option);
                           if($op_res===false)  throw new \Exception('修改规格失败');
                        }
                    }
                }
                $parms = input('params');
                if (isset($parms)) {
                    $params = json_decode($parms,1);

                    if(!empty($params) && is_array($params)){


                        $param_id_array = array_column($params, 'id');
                        $db_param = db("goods_param");
                        unset($where);
                        $where['goodsid'] = $id;
                        $db_param->where($where)->delete();
                        
                        foreach ($params as $k => $v) {
                            $param = array(
                                "title" => $v['title'],
                                "param" => serialize($v['param']),
                                "goodsid" => input('id')
                            );

                            if(!empty($v['id'])){
                                $param['id'] = $v['id'];
                            }

                            $pa_res= $db_param->insert($param);
                            if($pa_res===false)  throw new \Exception('修改属性失败');
                        }
                    }
 
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return array("message"=>$e->getMessage());
            }

        } else {
            Db::startTrans();
            try {
                $res =$db_goods->insertGetId($data);
                if(!$res)  throw new \Exception('发布失败');
                $specs = input('specs');
                if (isset($specs)) {
                    $specs = json_decode($specs,1);
                    if(!empty($specs) && is_array($specs)){


                        $db_option = db("goods_option");
                        foreach ( $specs as $k => $v) {
                            $option = array(
                                "title" => $v['title'],
                                "stock" => $v['stock'],
                                "price" => $v['price'],
                                "goodsid" => $res,
                            );
                           $op_add=$db_option->insert($option);
                            if(!$op_add)  throw new \Exception('添加规格失败');
                        }
                    }
                }
                $parms = input('params');
                if (isset($parms)) {

                    $params = json_decode($parms,1);

                    if(!empty($params) && is_array($params)){


                        $db_param = db("goods_param");
                        foreach ($params as $k => $v) {
                            $param = array(
                                "title" => $v['title'],
                                "param" => serialize($v['param']),
                                "goodsid" => $res,
                            );
                            $pa_add=$db_param->insert($param);
                            if(!$pa_add)  throw new \Exception('添加属性失败');
                        }
                    }
                }
         Db::commit();
        } catch (\Exception $e) {
        Db::rollback();
                return array("message"=>$e->getMessage());
    }
            if ($res === false) return array("message" => '操作失败');
            return array();
        }
        }
        $goods = (new System())->goods_detail();
        foreach($goods['params'] as &$v){
            $v['param']=$v['param'];
        }
        $this->assign("data", $goods);
        $category=(new System())->category();
        $this->assign("category",$category);
        return $this->fetch();
    }
    public function optiontpl()
    {
        return $this->fetch();
    }
    public function paramtpl()
    {
        return $this->fetch();
    }
    /**
     * @return 分类列表
     */
    public function category()
    {
        $category=(new System())->category();
        $this->assign("category",$category);
        return $this->fetch();
    }
    /**
     * @return 分类添加与修改
     */
    public function cateadd()
    {
        if(input("id")) {
            $category = (new System())->category_detail();
            $this->assign("category", $category);
        }
        if(request()->isPost()){
            $result = (new System())->category_edit();
            if(isset($result['message'])){
                $this->error($result['message']);
            }else{
                $this->redirect(url('goods/category'));
            }
        }
        return $this->fetch();
    }
    /**
     * @return 分类删除
     */
    public function cate_del()
    {
        if(request()->isPost()){
            $result = (new System())->category_del();
            if(isset($result['message'])){
               $this->error($result['message']);
            }else{
               echo 1;
            }
        }
    }
    /*
    *检测商品规格是否有空值
    */
    public function is_empty_specs($specs){
        $is_empty_specs = false;
        foreach($specs as $v){
            if(empty($v['title']) || empty($v['stock']) || empty($v['price'])){
                $is_empty_specs = true;
                break;
            }
        }

        return $is_empty_specs;
    }

    /**
    *检测商品属性是否有空值
    */
    public function is_empty_params($params){
        $is_empty_params = false;
        foreach($params as $v){
            if(empty($v['title']) || empty($v['param'])){
                $is_empty_params = true;
                break;
            }
        }

        return $is_empty_params;
    }

    //    删除图片a:2:{i:0;s:46:"/20190130/5ef16972855db0cb56c8e34fa45d7f06.png";i:1;s:45:"20190130/cc176c5142eb3820ac227ffc793d27c8.png";}
    public function delImg()
    {
        $index = input('index');
        $id = input('id');
        if(!$index && !$id )$this->error('参数有误');
        $dataimg = db('goods')->where('id', $id)->value('imgs');
        $dataimg = unserialize($dataimg);

        if(empty($dataimg[$index]))$this->error('数据不存在！');
        $file = ROOT_PATH . 'public' . $dataimg[$index];
        if(file_exists($file)) {
            unlink($file);
        }
        unset($dataimg[$index]);
        if(!empty($dataimg)){
            $data['imgs'] =serialize($dataimg);
        }else{
            $data['imgs'] = '';
        }
        $res = db('goods')->where('id='.$id)->update($data);
        if(!$res) $this->error('删除失败');
        $this->success("删除成功!",url('goods/goodsedit',array('id'=>$id)));
    }
}
